package com.beone.smart.smartBeauty.config;

import com.beone.smart.smartBeauty.dao.PersonInfoDao;
import com.beone.smart.smartBeauty.exception.GlobalException;
import com.beone.smart.smartBeauty.model.entity.PersonInfoConfigDO;
import com.beone.smart.smartBeauty.model.result.ResultTool;
import com.beone.smart.smartBeauty.utils.JwtUtils;
import com.github.eugeneheen.berry.kit.security.token.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by bruce on 20/2/27 -- 15:19
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static String JWT = "x-user-token";
    public static String USER_ID = "USER_ID";
    public static String USER_NAME = "USER_NAME";
    @Autowired
    private PersonInfoDao personInfoDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String url = request.getRequestURL().toString();
        log.info("====拦截到了方法：{}，请求的url是====", url);
        if (url.contains("/mobileAppHome/")
                || url.contains("/shopCar/")
                || url.contains("/mobileAppPersonCenter/")) {
            String token = request.getHeader(JWT);
            log.info("验证token:{}", token);
            if (StringUtils.isEmpty(token)) {
                throw new GlobalException(ResultTool.HttpResponseCode.UNAUTHORIZED, "token无效");
            }
            JwtToken jwtToken = JwtUtils.getUser(token);
            /**
             * 判断uid是否在数据库已经存在，不存在就新增用户
             */
            insertPersonInfo(jwtToken);
            /**
             * 设值进去
             */
            request.setAttribute(USER_ID, jwtToken.getId());
            request.setAttribute(USER_NAME, jwtToken.getUserName());
            log.info("uid为:{}", jwtToken.getId());
        }
        // 返回 true 才会继续执行，返回 false 则取消当前请求
        return true;
    }

    private void insertPersonInfo(JwtToken jwtToken) {
        String uid = jwtToken.getId();
        PersonInfoConfigDO personInfo = personInfoDao.getUserInfo(uid);
        if (personInfo == null) {
            PersonInfoConfigDO personInfoConfigDO = new PersonInfoConfigDO();
            personInfoConfigDO.setUserId(uid);
            personInfoConfigDO.setCurrentWeight(60.0);
            personInfoConfigDO.setExpectWeight(60.0);
            personInfoConfigDO.setHeight(175.0);
            personInfoConfigDO.setAge(20);
            personInfoConfigDO.setNickName(jwtToken.getUserName());
            personInfoDao.insert(personInfoConfigDO);
        }
    }
}
